package com.cci.kangdao.controller;

import com.cci.kangdao.crmapi.CRMServiceConst;
import com.cci.kangdao.utilTool.ParameterTool;
import com.cci.kangdao.utilTool.PublicTool;
import com.cci.kangdao.utilTool.SmsTool;
import com.cci.kangdao.utilTool.SmsUtils;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Yaxi Zhang
 * @date 2021/10/19
 */
@Controller
public class SmsController {
    private Logger log = Logger.getLogger(this.getClass().getName());

    private static final String regExp = "^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$";

    /**
     * 鸿联短信发送接口
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/sendSms.aspx")
    public String sendSms(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> map = ParameterTool.getParameterRequest(request, true);
            Map<String, Object> headerMap = this.getHeadersInfo(request);
            // 验证token是否对应
            if (!headerMap.containsKey(CRMServiceConst.CRM_REQUEST_HEADER_TOKEN)
                    || !map.containsKey(CRMServiceConst.CRM_REQUEST_COMPANY)
                    || !map.containsKey(CRMServiceConst.CRM_REQUEST_SYSTEMTIME)) {
                this.missingNecessaryParams(response, "缺少请求参数");
                return null;
            }
            String token = headerMap.get("token").toString();
            String company = map.get(CRMServiceConst.CRM_REQUEST_COMPANY).toString();
            String systemTime = map.get(CRMServiceConst.CRM_REQUEST_SYSTEMTIME).toString();
            if (token.length() > 0 && company.length() > 0 && systemTime.length() > 0) {
                String md5ToToken = PublicTool.compute(String.format("%s+%s", company, systemTime));
                if (!token.equals(md5ToToken)) {
                    this.missingNecessaryParams(response, "请求参数传递不正确");
                    return null;
                }
            } else {
                this.missingNecessaryParams(response, "必须参数不能为空");
                return null;
            }

            String phone = String.valueOf(map.get("phone"));
            String smsText = String.valueOf(map.get("smsText"));
            if (StringUtils.isBlank(phone) || !phone.matches(regExp)) {
                this.missingNecessaryParams(response, "缺少请求参数");
                return null;
            }
            String res = "";
            /**
             * 注释不再需要的短信工具类
             * sxt 20230814
             * Header Manipulation
             */
            //String res = SmsTool.sendSms1(phone, smsText);
            if (res.isEmpty()) {
                ParameterTool.writeErrorResponse(response);
                return null;
            }
            ParameterTool.writeSuccessResponse(response, res);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ParameterTool.writeResponse(response, e.getMessage());
        }
        return null;
    }


    /**
     * get request headers
     *
     * @param @param  request
     * @param @return
     * @return Map<String, String>
     * @throws
     * @Title: getHeadersInfo
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    private Map<String, Object> getHeadersInfo(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

    /**
     * 缺少必须参数
     *
     * @param @param response
     * @return void
     * @throws
     * @Title: missingNecessaryParams
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    private void missingNecessaryParams(HttpServletResponse response, String message) {
        //暂无此方法
        JSONObject obj = new JSONObject();
        obj.put("status", 1);
        obj.put("msg", message);
        obj.put("data", "");
        ParameterTool.writeResponse(response, obj.toString());
        obj = null;
    }


    //外部系统发送短信接口   这里只做是否发送短信的判断以及保存报名单，上行短信的逻辑   发送短信的动作交给调用方
    @RequestMapping("/outSystemSendSms.aspx")
    public String outSystemSendSms(HttpServletRequest request, HttpServletResponse response) {
        try{
            Map<String, Object> map = ParameterTool.getParameterRequest(request, true);
            String phone = MapUtils.getString(map,"phone","");
            String msg = MapUtils.getString(map,"msg","");
            ParameterTool.writeResponse(response, SmsUtils.outSystemSendMessage(phone,msg));
        }catch(Exception ex){
            log.error(ex.getMessage(),ex);

            String msg = "{\"status\": -99,\"msg\": \"未知错误\"}";
            ParameterTool.writeResponse(response, msg);
        }
        return null;
    }
}
